package com.xxg.imagemanager.baidu;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.imagesearch.AipImageSearch;
import com.xxg.imagemanager.domain.result.ImageObject;
import com.xxg.imagemanager.domain.result.ImageResult;
import com.xxg.imagemanager.service.QpsComponent;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图像检索管理器
 *
 * @author xuxiaogang
 * @date 2021-12-10
 */
@Component
public class ImageRetrieval {
    private static final Logger logger = LoggerFactory.getLogger(ImageRetrieval.class);
    private final static String APP_ID = "25344221";
    private final static String API_KEY = "WGQCwbXZXHssN1b7HLrmmnPG";
    private final static String SECRET_KEY = "gAGqRzxbSwTV3510VAYtoNVXcg1SV1lw";
    private final static String ENDPOINT = "https://slsbu.su.bcebos.com/";
    private final AipImageSearch client;
    private final QpsComponent qpsComponent;

    public ImageRetrieval() {
        client = new AipImageSearch(APP_ID, API_KEY, SECRET_KEY);
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        qpsComponent = new QpsComponent(2);
    }

    /**
     * 批量创建图片索引
     *
     * @param images 图片信息
     */
    public void batchCreateImageIndex(List<ImageObject> images) {
        logger.info("批量创建图片索引");
        for (ImageObject object : images) {
            createImageIndex(object.getKey(), JSON.toJSONString(object.getMap()));
        }
    }

    @Async("productAddExecutor")
    public void createImageIndex(String image, String brief) {
        qpsComponent.acquireQps();
        String imageUrl = ENDPOINT + image;
        HashMap<String, String> options = new HashMap<>(3);
        // 带货平台分类 2
        options.put("class_id1", "2");
        // 商品分类 1-灯具
        options.put("class_id2", "1");
        JSONObject jsonObject = client.productAddUrl(imageUrl, brief, options);
        logger.info(jsonObject.toString() + " " + brief);
    }

    /**
     * 搜索图片
     *
     * @param file 图片文件
     */
    public void searchByPic(byte[] file) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<>(6);
        options.put("class_id1", "2");
        options.put("class_id2", "1");
        options.put("pn", "0");
        options.put("rn", "50");
        JSONObject res = client.productSearch(file, options);
        if (res.has("result")) {
            Object result = res.get("result");
            List<ImageResult> list = JSON.parseArray(result.toString(), ImageResult.class);
            System.out.println(list.size());
        }
    }
}
